package com.leetcode.solution.s9x;

import com.leetcode.solution.model.ListNode;

public class ReverseBetween92 {
    public static void main(String[] args) {
        ListNode node = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
        ListNode head = new ReverseBetween92().reverseBetween(node, 2, 4);
        while (head != null) {
            System.out.print(head.val + ", ");
            head = head.next;
        }
    }

    public ListNode reverseBetween(ListNode head, int left, int right) {
        ListNode root = new ListNode(-1, head);
        ListNode pre = root;

        for (int i = 0; i < left - 1; i++) {
            pre = pre.next;
        }

        ListNode curr = pre.next;
        ListNode next;
        for (int i = 0; i < right - left; i++) {
            next = curr.next;

            curr.next = next.next;
            next.next = pre.next;
            pre.next = next;

        }

        return root.next;
    }

}
